package com.yiyi.credit.manage.sso.service.inner;

import com.yiyi.credit.manage.sso.cache.RedisManager;
import com.yiyi.credit.manage.sso.common.Constant;
import com.yiyi.credit.manage.sso.common.MD5Util;
import com.yiyi.credit.manage.sso.common.exception.ResponseCode;
import com.yiyi.credit.manage.sso.common.exception.ServiceException;
import com.yiyi.credit.manage.sso.common.page.PageUtils;
import com.yiyi.credit.manage.sso.common.page.Pagination;
import com.yiyi.credit.manage.sso.mapper.SysUserInfoMapper;
import com.yiyi.credit.manage.sso.mapper.SysUserMapper;
import com.yiyi.credit.manage.sso.mapper.SysUserRoleMapper;
import com.yiyi.credit.manage.sso.model.entity.SysUser;
import com.yiyi.credit.manage.sso.model.entity.SysUserInfo;
import com.yiyi.credit.manage.sso.model.entity.SysUserRole;
import com.yiyi.credit.manage.sso.model.system.UserAllInfo;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.*;

@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    SysUserMapper sysUserMapper;

    @Autowired
    SysUserInfoMapper sysUserInfoMapper;

    @Autowired
    SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    RedisManager redisManager;

    private static Logger logger = LoggerFactory.getLogger(SysUserServiceImpl.class);


    @Override
    public SysUser getUserByName(String userName) throws ServiceException {
        try {
            return sysUserMapper.selectOne(new SysUser(userName));
        } catch (Exception e) {
            throw new ServiceException(ResponseCode.SERVICE_ERR);
        }
    }


    @Transactional
    @Override
    public void register(String userName, String password, Long status, SysUserInfo sysUserInfo) throws ServiceException {
        try {
            SysUser sysUser = new SysUser();
            //sysUser.setId(redisManager.increaseOne(TableConstants.TB_SYS_USER));
            sysUser.setUserName(userName);
            sysUser.setPassword(MD5Util.encoderByMd5(password));
            sysUser.setStatus(status);
            sysUser.setIsSysUser((long)2);
            sysUser.setShopId((long)0);
            sysUser.setCreateTime(new Date().getTime());
            sysUser.setUpdateTime(new Date().getTime());
            sysUserMapper.insert(sysUser);

            sysUser = getSysUserByUserName(sysUser.getUserName()).get(0);
            //sysUserInfo.setId(redisManager.increaseOne(TableConstants.TB_SYS_USER_INFO));
            sysUserInfo.setUid(sysUser.getId());
            sysUserInfo.setSex(0L);
            sysUserInfo.setCreateTime(new Date().getTime());
            sysUserInfo.setUpdateTime(new Date().getTime());
            //sysUserMapper.insert(sysUser);
            sysUserInfoMapper.insert(sysUserInfo);

        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new ServiceException(ResponseCode.USER_REGISTER_FAIL);
        }
    }


    @Override
    public Pagination getSysUserPageList(String userName, Pagination pagination) throws ServiceException {

        SysUser sysUser = new SysUser();
        if (StringUtils.isNotBlank(userName)) {
            sysUser.setUserName(userName);
        }
        Integer count = sysUserMapper.selectCount(sysUser);
        pagination.setRecordsTotal(count.longValue());
        pagination.setPage(PageUtils.getPage(count.longValue(), pagination.getLength()));
        if (count > Constant.LONG_ZERO) {
            pagination.setData(sysUserMapper.getPageData(userName, pagination));
        }
        return pagination;
    }


    @Override
    public Integer updateSysUser(SysUser sysUser) throws ServiceException {

        //判断名称是否存在
        SysUser checkSysUser = sysUserMapper.selectByPrimaryKey(sysUser.getId());
        if (checkSysUser == null) {
            throw new ServiceException(ResponseCode.USER_NOT_EXIST);
        }
        try {
            sysUser.setUpdateTime(new Date().getTime());
            return sysUserMapper.updateByPrimaryKeySelective(sysUser);
        } catch (Exception e) {
            throw new ServiceException(ResponseCode.SERVICE_ERR);
        }
    }



    @Override
    public Object updatePassword(Long sysUserId, String oldPassword, String newPassword) throws Exception {

        //判断名称是否存在
        SysUser checkSysUser = sysUserMapper.selectByPrimaryKey(sysUserId);
        if (checkSysUser == null) {
            throw new ServiceException(ResponseCode.USER_NOT_EXIST);
        }
        if (!checkSysUser.getPassword().equals(MD5Util.encoderByMd5(oldPassword))) {
            throw new ServiceException(ResponseCode.PWD_WRONG);
        }
        try {
            SysUser sysUser = new SysUser();
            sysUser.setId(checkSysUser.getId());
            sysUser.setUserName(checkSysUser.getUserName());
            sysUser.setPassword(MD5Util.encoderByMd5(newPassword));
            sysUser.setStatus(checkSysUser.getStatus());
            sysUser.setCreateTime(checkSysUser.getCreateTime());
            sysUser.setUpdateTime(new Date().getTime());
            return sysUserMapper.updateByPrimaryKeySelective(sysUser);
        } catch (Exception e) {
            throw new ServiceException(ResponseCode.SERVICE_ERR);
        }
    }



    @Override
    public Integer deleteSysUserRole(SysUser sysUser) throws ServiceException {

        //判断名称是否存在
        SysUser checkSysUser = getSysUserById(sysUser.getId());
        if (checkSysUser == null) {
            throw new ServiceException(ResponseCode.USER_NOT_EXIST);
        }


        Example roleExample = new Example(SysUserRole.class);
        roleExample.createCriteria().andEqualTo("userId", sysUser.getId());
        return sysUserRoleMapper.deleteByExample(roleExample);

    }



    @Override
    public Integer deleteSysUser(SysUser sysUser) throws ServiceException {

        //判断名称是否存在
        SysUser checkSysUser = getSysUserById(sysUser.getId());
        if (checkSysUser == null) {
            throw new ServiceException(ResponseCode.USER_NOT_EXIST);
        }


        Example roleExample = new Example(SysUserRole.class);
        roleExample.createCriteria().andEqualTo("userId", sysUser.getId());
        List<SysUserRole> sysUserRoleList = sysUserRoleMapper.selectByExample(roleExample);

        if (sysUserRoleList.size() > 0) {
            throw new ServiceException(ResponseCode.USER_BAND_ROLE);
        }


        sysUserMapper.deleteByPrimaryKey(sysUser);

        Example example = new Example(SysUserInfo.class);
        example.createCriteria().andEqualTo("uid", sysUser.getId());
        return sysUserInfoMapper.deleteByExample(example);
    }



    @Override
    public SysUser getSysUserById(Long id) throws ServiceException {
        return sysUserMapper.selectByPrimaryKey(id);
    }


    @Override
    public List<SysUser> getSysUserByUserName(String userName) throws ServiceException {
        Example example = new Example(SysUser.class);
        example.createCriteria().andEqualTo("userName", userName);
        return sysUserMapper.selectByExample(example);
    }


    @Override
    public Map<String, String> getSysUserByUserName1(String userName) throws ServiceException {
        return sysUserInfoMapper.getSysUserByUserName(userName);
    }



    public Pagination getUserAllInfoList(Long sysInfoId, String userName, String realName, Long roleNameId, Long status, Pagination pagination) throws ServiceException {

        Long count = sysUserMapper.getSysRoleList(sysInfoId, userName, realName, roleNameId, status, pagination);
        pagination.setRecordsTotal(count);
        pagination.setPage(PageUtils.getPage(count, pagination.getLength()));
        if (count > Constant.LONG_ZERO) {
            List<Map<String, Object>> sysUsers = sysUserMapper.getUserAllInfoPageData(sysInfoId, userName, realName, roleNameId, status, pagination);
            List<UserAllInfo> result = new ArrayList<>();
            Iterator iterator = sysUsers.iterator();
            while (iterator.hasNext()) {
                UserAllInfo userAllInfo = new UserAllInfo();
                Map<String, Object> map = (Map) iterator.next();
                userAllInfo.setId((Long) map.get("id"));
                userAllInfo.setRealName((String) map.get("realName"));
                userAllInfo.setUserName((String) map.get("userName"));
                userAllInfo.setPhone((String) map.get("phone"));
                userAllInfo.setRoleName((String) map.get("roleName"));
                userAllInfo.setStatus((Long) map.get("status"));
                userAllInfo.setRoleId((Long) map.get("roleId"));
                result.add(userAllInfo);
            }
            pagination.setData(result);
        }
        return pagination;

    }


    @Override
    public List<UserAllInfo> getUserInfoByIds(Long sysInfoId, String ids) throws ServiceException {
        String[] checkIds = ids.split(",");
        List<UserAllInfo> result = new ArrayList<>();
        for (int i = 0; i < checkIds.length; i++) {
            Long userId = Long.parseLong(checkIds[i]);
            UserAllInfo userAllInfo = new UserAllInfo();
            Map<String, Object> map = sysUserMapper.getUserInfoById(sysInfoId, userId);
            if (map == null) {
                result.add(userAllInfo);
                continue;
            }
            userAllInfo.setId((Long) map.get("id"));
            userAllInfo.setRealName((String) map.get("realName"));
            userAllInfo.setUserName((String) map.get("userName"));
            userAllInfo.setPhone((String) map.get("phone"));
            userAllInfo.setRoleName((String) map.get("roleName"));
            result.add(userAllInfo);
        }


        return result;
    }

}


